import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'// nprogress样式文件
import { whiteList } from '../framework/profile';
import { store } from '../store';
import AsyncRoutes from './routes/index'
import { notBlankForString } from '/@/kit/blank-kit';
import { getAccessToken } from '/@/kit/token-kit';
import { baseUrl } from '/@/framework/profile/index'
import { BasicLayout } from '/@/layouts';

NProgress.configure({
    easing: 'ease',  // 动画方式    
    speed: 500,  // 递增进度条的速度    
    showSpinner: false, // 是否显示加载ico    
    trickleSpeed: 200, // 自动递增间隔    
    minimum: 0.3 // 初始化时的最小百分比
})

const BasicRoutes: Array<RouteRecordRaw> = [
    {
        path: '/',
        name: 'Home',
        redirect: '/dashboard',
    },
    {
        path: '/login',
        name: 'Login',
        component: () => import('/@/views/login/index.vue')
    }
]
/**
 * 404 匹配路由
 */
const notFundRoute: RouteRecordRaw = {
    path: '/:pathMatch(.*)*', name: 'not-found', component: () => import('/@/views/error/notfound.vue')
}

/**
 * redirect 路由
 */
const redirectRoute: RouteRecordRaw = {
    path: '/redirect',
    name: 'redirectMain',
    component: BasicLayout,
    children: [
        {
            path: '/redirect/:path(.*)',
            name: 'redirectPath',
            component: () => import('/@/components/plugin/redirect/index.vue')
        }
    ]
}
const routes = BasicRoutes.concat(AsyncRoutes);

export function createWebRouter() {
    return createRouter({
        //在码云上直接部署 history路由会有问题 二级目录spa文件的支持可能还不够
        history: createWebHistory(baseUrl),
        routes,
    })
}
const router = createWebRouter();

/**
 * 全局路由拦截配置
 */
router.beforeEach(async (to, from, next) => {
    NProgress.start();
    const accessToken = getAccessToken();
    if (notBlankForString(accessToken)) {
        if (to.path === '/login') {
            // 如果已经登录了 则到首页
            next({ path: '/' })
        } else {
            const hasUserId = store.state.user.userId;
            if (notBlankForString(hasUserId)) {
                next()
            } else {
                try {
                    //支持动态路由
                    await store.dispatch('user/getInfo');
                    //menus中储存的是菜单id
                    const userMenus = store.state.user.menus;
                    const routes = router.getRoutes();
                    routes.forEach((route) => {
                        if (route.path == "/" || route.path == "/login") return;
                        if (userMenus.indexOf(route.meta.menuId as string) == -1) router.removeRoute(route.name);
                    })
                    //加入 跳转路由
                    router.addRoute(redirectRoute);
                    //加入 未知路由定向到404
                    router.addRoute(notFundRoute);
                    next({
                        ...to,
                        replace: true
                    })
                } catch (error) {
                    // 删除token 并且跳转到登录页面
                    await store.dispatch('user/clearToken')
                    next({ path: '/login', query: { redirect: to.path } })
                }
            }
        }
    } else {
        /* has no token*/
        if (whiteList.indexOf(to.path) !== -1) {
            next()
        } else {
            next({ path: '/login', query: { redirect: to.path } })
        }
    }
});

//当路由跳转结束后
router.afterEach(() => {
    // 关闭进度条
    NProgress.done()
})

export default router;